<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-row :gutter="20" class="serch-box">
        <el-col :span="7">
          <!-- 搜索与添加区域 -->
          <!-- clearable	是否可清空 -->
          <el-input placeholder="请输入内容" v-model.trim="paramObj.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 数据表格区域 -->
      <!-- 当el-table元素中注入data对象数组后，在el-table-column中用prop属性来对应对象中的键名即可填入数据，
      用label属性来定义表格的列名。可以使用width属性来定义列宽。 -->
      <el-table :data="userList" style="width: 100%">
        <!-- 索引列 -->
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-switch v-model="scope.row.mg_state" @change="changeSwitchState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 插槽形式自定义列的渲染 -->
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
            <!-- enterable	鼠标是否可进入到 tooltip 中 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 数据分页效果 -->
      <div class="block">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="this.paramObj.pagenum" :page-sizes="[2, 5, 10]" :page-size="this.paramObj.pagesize"
          layout="total, sizes, prev, pager, next, jumper" :total="this.total">
        </el-pagination>
      </div>
      <!-- 添加用户的对话框 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" @close="resetAddForm">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="addForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="passWord">
            <el-input v-model="addForm.passWord"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户的对话框 -->
      <el-dialog title="修改用户" :visible.sync="editDialog" width="30%" @close="resetEditForm">
        <el-form ref="editFormRef" :model=editForm width="80px" :rules="addFormRules">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialog = false;">取 消</el-button>
          <el-button type="primary" @click="addEditUser">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 邮箱验证规则
    var checkEmail = (rule, value, cb) => {
      // 邮箱验证的正则表达式
      const regEmail = /^([a-zA-Z0-9-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 验证成功
        return cb();
      }
      // 验证失败
      cb(new Error("请输入合法的邮箱"));
    };
    var checkMobile = (rule, value, cb) => {
      // 手机号验证的正则表达式
      const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regMobile.test(value)) {
        // 验证成功
        return cb();
      }
      // 验证失败
      cb(new Error("请输入合法的手机号"));
    };
    return {
      paramObj: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      editDialog: false,
      addForm: {
        userName: '',
        passWord: '',
        email: '',
        mobile: ''
      },
      editForm: {},
      addFormRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在1到 5 个字符', trigger: 'blur' }
        ],
        passWord: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    // 获取用户数据列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.paramObj });
      // console.log(res);
      if (res.meta.status !== 200) return this.$msg.error("获取用户列表数据失败");
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 监听pagesize的改变
    handleSizeChange(pageSize) {
      // console.log(`每页 几 条`);
      this.paramObj.pagesize = pageSize;
      // 重新加载页面
      this.getUserList();
    },
    // 监听页码值的改变
    handleCurrentChange(pageNum) {
      // console.log("当前页")
      this.paramObj.pagenum = pageNum;
      this.getUserList();
    },
    // 监听开关状态改变
    async changeSwitchState(userInfo) {
      // console.log(userInfo);
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
      // console.log(res);
      if (res.meta.status !== 200) {
        // 重置页面上开关效果
        userInfo.msg_state = !userInfo.msg_state;
        return this.$msg.error("状态设置失败");
      }
      this.$msg.success(res.meta.msg);
      // res.data.mg_state = userInfo.mg_state;
    },
    // 重置添加表单
    resetAddForm() {
      this.$refs.addFormRef.resetFields();
    },
    // 重置编辑用户表单
    resetEditForm() {
      this.$refs.editFormRef.resetFields();
    },
    // 添加用户：表单预校验后发起请求
    // 存在问题
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addForm);
          console.log(res)
          if (res.meta.status !== 201) return this.$msg.error("用户添加失败");
          // 添加用户成功
          this.$msg.success(res.meta.msg);
          // 隐藏对话框
          this.dialogVisible = false;
          // 重新渲染
          this.getUserList();
        }
      })
    },
    // 展示编辑对话框
    async showEditDialog(id) {
      this.editDialog = true;
      const { data: res } = await this.$http.get(`users/${id}`);
      // console.log(res);
      if (res.meta.status !== 200) return this.$msg.error("修改用户信息失败");
      this.editForm = res.data;

    },
    // 编辑用户提交
    addEditUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`users/${this.editForm.id}`, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          });
          // console.log(res)
          if (res.meta.status !== 200) return this.$msg.error("用户添加失败");
          // 添加用户成功
          this.$msg.success(res.meta.msg);
          // 重新渲染
          this.getUserList();
          // 关闭编辑用户对话框
          this.editDialog = false;
        }
      })
    },
    // 删除用户
    removeUser(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`users/${id}`).then((res) => {
          // console.log(res)
          if (res.status !== 200) return this.$msg.error("删除用户失败");
          this.$msg({
            type: 'success',
            message: '删除成功!'
          });
          // 重新渲染
          this.getUserList();
        });
      }).catch(() => {
        this.$msg({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
  created() {
    this.getUserList();
  },

}
</script>

<style lang="less" scoped>
</style>